import React from 'react';
import {Col, Row, Modal, Descriptions, Badge, Skeleton, DatePicker} from 'antd';
import styles from './index.less';
import {connect} from "dva";
import {trigger} from "@/utils/utils";
import {dateFormat, currentTime, getMockTime} from "@/utils/time";
import echarts from 'echarts'
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import ItemDetail from "@/pages/GaoLu/components/ItemDetail";
import moment from "moment";

class AutoScore extends React.Component {
  stopLoop = false;
  state = {
    scoreQuntile: null,
    count: null,
    current: currentTime(),
    autoScore: {
      curScore: {
        CG_LT_GL_GL04_Score: 0,
        CG_LT_GL_GL04_Status: '异常',
        DateTime: ''
      },
      lastHourScore: {
        CG_LT_GL_GL04_Score: 0,
        CG_LT_GL_GL04_Status: '异常',
        DateTime: ''
      },
      status: {}
    },
    visible: false
  };

  defaultDisplay = ["CG_LT_GL_GL04_TQXZS_status",
    "CG_LT_GL_GL04_FZWD_status",
    "CG_LT_GL_GL04_LFLL_status",
    "CG_LT_GL_GL04_FYLL_status",
    "CG_LT_GL_GL04_FCokeRate_status",
    "CG_LT_GL_GL04_FCoalRate_status",
    "CG_LT_GL_GL04_RFWD_status",
    "CG_LT_GL_GL04_SBYCZB_status",
    "CG_LT_GL_GL04_XBYCZB_status",];

 async componentDidMount() {
    const {dispatch} = this.props;

    const payload = await getMockTime("GaoLu")

    this.scoreQuntileReq = requestAnimationFrame(() => dispatch({type: 'gaolu/getScoreQuntile',payload:{
      start:dateFormat(payload.start),
        end:dateFormat(payload.end)
      }}));
    this.autoScoreReq = requestAnimationFrame(() =>
      trigger(
        async () => {
          const payload =await getMockTime("GaoLu")
          if (this.state.count === 0) {


            this.state.count += 1;
            if (this.state.count >= 50) {
              this.state.count = null;
              this.state.current = payload.current;
              dispatch({
                type: 'gaolu/autoScore',
                payload: {
                  end: dateFormat(payload.current)
                }
              });
              return
            }
          }
          dispatch({
            type: 'gaolu/autoScore',
            payload: {
              end: dateFormat(payload.current)
            }
          });

        },
        new Date().valueOf(),
        10 * 1000,
        true,
        () => this.stopLoop));

    this.setState({current:payload.current})
  }


  componentWillUnmount() {
    cancelAnimationFrame(this.autoScoreReq);
    cancelAnimationFrame(this.scoreQuntileReq);
    this.stopLoop = true
  }


  static getDerivedStateFromProps(nextProps, prevState) {
    const {autoScore, scoreQuntile} = nextProps;
    // 及时更新display
    if (autoScore && autoScore !== prevState.autoScore) {
      return {
        autoScore
      }
    }

    if (scoreQuntile !== prevState.scoreQuntile && scoreQuntile) {
      return {
        scoreQuntile
      }
    }

    return null;
  }

  timePick = (value) => {
    this.state.current = value.toDate();
    this.state.count = 0;
    this.getAutoScore();
    // this.getScoreQuntile();
  };

  getAutoScore = () => {
    this.props.dispatch({
      type: 'gaolu/autoScore',
      payload: {
        end: dateFormat(this.state.current),
      }
    });
  };

  getStatus = status => {
    if (status === '数据异常') {
      return 'error'
    }
    if (status === '正常') {
      return 'processing'
    }

    if (status === '优秀') {
      return 'success'
    }

    if (status === '波动') {
      return 'warning'
    }
    if (status === '无') {
      return 'processing'
    }

    return 'error'
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = e => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  render() {

    const {autoScore, current} = this.state;
    const format = 'YYYY-MM-DD HH';
    let curScore = '无', curStatus = '无', curTime = "无";
    let lastHourScore = '无', lastHourStatus = '无', lastTime = "无";

    if (autoScore.curScore && autoScore.curScore.CG_LT_GL_GL04_Score) {
      curScore = autoScore.curScore.CG_LT_GL_GL04_Score;
      curStatus = autoScore.curScore.CG_LT_GL_GL04_Status;
      curTime = autoScore.curScore.DateTime;
    }
    if (autoScore.lastHourScore && autoScore.lastHourScore.CG_LT_GL_GL04_Score) {
      lastHourScore = autoScore.lastHourScore.CG_LT_GL_GL04_Score;
      lastHourStatus = autoScore.lastHourScore.CG_LT_GL_GL04_Status;
      lastTime = autoScore.lastHourScore.DateTime;

    }
    const statusDict = autoScore.statusDict;
    const statusWarning = autoScore.statusWarning;
    const reasonScope = autoScore.reasonScope;
    const stageWarning = autoScore.stageWarning;
    const desc = autoScore.desc;
    // const detail = Object.entries(autoScore.status).sort(
    //   (a, b) => a[1] > b[1]
    // ).slice(0, 5);

    // const detail = Object.entries(autoScore.status).slice(0, 8);

    let dom = undefined;
    if (statusDict) {
      dom = this.defaultDisplay.map((item) => (
        <Row key={item}>
          <Col span={8}>
            {statusDict[item]}
          </Col>
          <Col span={8}>
            {autoScore.status[item]}
          </Col>
          <Col span={8}>
            {reasonScope[item]}
          </Col>
          <br/>
        </Row>));
    }
    return (
      <div style={{height: '100%'}}>
        <DatePicker
          showTime
          format={format}
          placeholder="选择时间"
          defaultValue={moment(current, format)}
          key={Math.random()}
          onChange={this.timePick}
        />
        <Descriptions title="" bordered>
          <Descriptions.Item label="当前分数" span={1}>{curScore}</Descriptions.Item>
          <Descriptions.Item label="评价" span={1}>
            <Badge status={this.getStatus(curStatus)} text={curStatus}/>
          </Descriptions.Item>
          <Descriptions.Item label="当前时间" span={1}>{curTime}</Descriptions.Item>
          <Descriptions.Item label="上次分数" span={1}>{lastHourScore}</Descriptions.Item>
          <Descriptions.Item label="评价" span={1}>
            <Badge status={this.getStatus(lastHourStatus)} text={lastHourStatus}/>
          </Descriptions.Item>
          <Descriptions.Item label="上次时间" span={1}>{lastTime}</Descriptions.Item>
          <Descriptions.Item label="分数趋势预警" span={2}>{desc}</Descriptions.Item>
          <Descriptions.Item label="状态预警" span={2}>{statusWarning}</Descriptions.Item>
          <Descriptions.Item label="炉况阶段预警" span={2}>{stageWarning}</Descriptions.Item>
          <Descriptions.Item label="失分项(与最佳范围比较)" span={1}>
            <div style={{height: 136}}>
              {dom}
            </div>
          </Descriptions.Item>

        </Descriptions>

        <div>
          <Row style={{marginTop: 22}}>
            <a className={styles.showMore} style={{float: 'right'}} onClick={this.showModal}>查看更多</a>
          </Row>
        </div>

        <Modal
          width="80%"
          // title="分数详情"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >

          <ItemDetail/>
        </Modal>

      </div>

    )
  }
}

export default connect(({gaolu}) => ({
  autoScore: gaolu.autoScore,
  scoreQuntile: gaolu.scoreQuntile
}))
(AutoScore);
